package com.yaowk.service.system.service.impl;

import com.yaowk.api.system.model.Permission;
import com.yaowk.api.system.service.IPermissionService;
import com.yaowk.service.common.BaseRepository;
import com.yaowk.service.common.BaseServiceImpl;
import com.yaowk.service.system.dao.MenuRepository;
import com.yaowk.service.system.dao.PermissionRepository;
import com.yaowk.service.system.dao.ResourceRepository;
import com.yaowk.service.system.entity.SysMenu;
import com.yaowk.service.system.entity.SysPermission;
import com.yaowk.service.system.entity.SysResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class PermissionServiceImpl extends BaseServiceImpl<Permission, SysPermission, Integer> implements IPermissionService {

    @Autowired
    private PermissionRepository dao;
    @Autowired
    private MenuRepository menuDao;
    @Autowired
    private ResourceRepository resourceDao;

    @Override
    protected BaseRepository<SysPermission, Integer> getDao() {
        return dao;
    }

    @Override
    protected SysPermission model2Entity(Permission model) {
        SysPermission sysPermission = null;
        if (!ObjectUtils.isEmpty(model)) {
            sysPermission = new SysPermission();
            sysPermission.setId(model.getId());
            sysPermission.setPermission(model.getPermission());
        }
        return sysPermission;
    }

    @Override
    protected Permission entity2model(SysPermission entity) {
        Permission permission = null;
        if (!ObjectUtils.isEmpty(entity)) {
            permission = new Permission();
            permission.setId(entity.getId());
            permission.setPermission(entity.getPermission());
        }
        return permission;
    }

    @Override
    public List<Permission> findPermissionsByMenuId(Integer menuId) {
        SysMenu sysMenu = menuDao.findOne(menuId);
        return entity2Model(sysMenu.getPermissions());
    }

    @Override
    public List<Permission> findPermissionsByResourceId(Integer resourceId) {
        SysResource sysResource = resourceDao.findOne(resourceId);
        return entity2Model(sysResource.getPermissions());
    }
}
